import {request} from "@/utils/service"
// @ts-ignore
import type { UploadFile } from 'element-plus'

// * 文件上传模块
export namespace Upload {
  export interface ResFileUrl {
    fileUrl: string;
  }
  export interface Container {
    file: UploadFile;
    hash: string;
    worker: any;
  }
  export interface FileChunk {
    file: Blob;
  }
  export interface specialRequest {
    url: string,
    method?: string,
    data: any,
    headers?: Record<string, string>
    onProgress?: any,
    requestList?: XMLHttpRequest[],
  }

  export interface verifyUpload {
    result: {
      shouldUpload: boolean,
      uploadedList: string[]
    }
  }

  export interface data {
    fileHash: string,
    s3UploadID?: string
    index: number,
    hash: string,
    chunk: Blob,
    size: number,
    percentage: number,
  }
}


export interface CustomerFileRow {
  id?: string
  name?: string
  fileName?: string
  size?: number
  customerId?: number
  desc?: string
  key?: string
  createdAt?: string
  updatedAt?: string
  fileInfo?: object
  _VXE_ID?: string
}
export interface uploadFile {
  filename: string
  fileHash: string
  size?: number
}

export type GetFileResponseData = ApiResponseData<{
  list: CustomerFileRow[]
  total: number
}>

/** 新增 */
export function addCustomerFileApi(data: CustomerFileRow) {
  return request<ApiResponseData<null>>({
    url: "/customer/file",
    method: "post",
    data
  })
}

/** 修改 */
export function updateCustomerFileApi(data: CustomerFileRow) {
  return request<ApiResponseData<null>>({
    url: "/customer/file",
    method: "put",
    data
  })
}

/** 查 */
export function getCustomerFileApi(params: CustomerFileRow) {
  return request<ApiResponseData<GetFileResponseData>>({
    url: "/customer/file",
    method: "get",
    params
  })
}

/** 删 */
export function deleteCustomerFileApi(id: string, key: string) {
  return request({
    url: `customer/file/${id}`,
    method: "delete",
    params: {
      key
    }
  })
}



/** 获取已上传的源信息 */
export function uploadFileApi(data: uploadFile) {
  return request<ApiResponseData<null>>({
    url: "/public/upload/verify",
    method: "post",
    data
  })
}


/** 大文件上传的单独的request */
export function bigUploadRequest({ url, method = 'post', data, headers = {}, onProgress = (e: any) => e, requestList }: Upload.specialRequest): Promise<Upload.verifyUpload> {
  return new Promise((resolve) => {
    const xhr = new XMLHttpRequest()
    // 一个无符号长整型（unsigned long）数字，表示该请求的最大请求时间（毫秒），若超出该时间，请求会自动终止。
    xhr.timeout = 300000
    xhr.upload.onprogress = onProgress
    xhr.open(method, url)
    Object.keys(headers).forEach((key) =>
      xhr.setRequestHeader(key, headers[key])
    )
    xhr.ontimeout = (e: ProgressEvent) => {
      console.log('请求超时')
    }
    xhr.send(data)
    // XMLHttpRequest请求成功完成时触发；
    xhr.onload = (e: ProgressEvent) => {
      // 将请求成功的 xhr 从列表中删除
      if (requestList) {
        //@ts-ignore
        const xhrIndex = requestList.findIndex((item) => item === xhr)
        requestList.splice(xhrIndex, 1)
      }
      let target = <XMLHttpRequest>e.target
      let result = JSON.parse(target.response)
      resolve({
        result
      })
    }
    // 当请求结束时触发, 无论请求成功(load)还是失败(abort 或 error)。也可以使用 onloadend 属性。
    xhr.onloadend = (e) => e
    // 暴露当前 xhr 给外部
    requestList?.push(xhr)
  })
}

/** 通知服务端合并分片 */
export function mergeChunkFile(data: uploadFile) {
  return request<ApiResponseData<null>>({
    url: "/public/upload/merge",
    method: "post",
    data
  })
}
